package com.smart.seckilldemo.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 缓存判断工具类
 */
@SuppressWarnings("ALL")
@Component
public class RedisJudgeUtils {

    @Resource
    RedisTemplate<String, Object> redisTemplate;
    //缓存的有效时间
    private final Integer Time = 3000;

    /**
     * 判断key 是否有数据 无则存如Null
     *
     * @param Key 缓存key
     * @return
     */
    public Object getRed(String Key) {
        if (redisTemplate.hasKey(Key)) {
            //该key 是否有数据
            return redisTemplate.opsForValue().get(Key);
        } else {
            //防止缓存穿透存入空值
            redisTemplate.opsForValue().set(Key, null, 10, TimeUnit.SECONDS);
            return null;
        }
    }

    /**
     * 将数据存入缓存中
     * @param key 缓存key
     * @param obj 缓存对象
     */
    public void setRed(String key, Object obj) {
        redisTemplate.opsForValue().set(key, obj, Time, TimeUnit.SECONDS);
    }

    /**
     * 删除缓存信息
     *
     * @param key 缓存key
     */
    public void deleteRed(String key) {
        Boolean  delete = redisTemplate.delete(key);
    }


}